package com.xy.filter;

import com.alibaba.fastjson.JSON;
import com.xy.jwt.JWToo;
import com.xy.vo.R;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class LoginFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        String path = request.getRequestURI();
        String method = request.getMethod();
        if("/login".equals(path)&&"POST".equals(method)){
            //放行
            filterChain.doFilter(request,response);
            return;
        }

        //1. 从请求头中获取token令牌
        String token = request.getHeader("token");
        //2. 判断是否token为null
        if(StringUtils.isEmpty(token)){
            PrintWriter writer = response.getWriter();
            //3. 返回一个未登录的json数据.
            R r=new R(500,"未登录",null);
            String jsonString = JSON.toJSONString(r);
            writer.write(jsonString);
            writer.flush();
            writer.close();
            return;
        }

        //3. 验证token
        if(!JWToo.verify(token)){
            PrintWriter writer = response.getWriter();
            //3. 返回一个未登录的json数据.
            R r=new R(500,"token失效",null);
            String jsonString = JSON.toJSONString(r);
            writer.write(jsonString);
            writer.flush();
            writer.close();
            return;
        }
        //把当前用户的信息封装到Authentication对象中
        SecurityContext context = SecurityContextHolder.getContext();
        //Object principal,账号
        // Object credentials,密码 null
        //			Collection<? extends GrantedAuthority> authorities:权限
        Map<String, Object> userinfo = JWToo.getInfo(token, "userinfo");
        Object username = userinfo.get("username");
        List<String> permissions = (List<String>) userinfo.get("permissions");
        List<SimpleGrantedAuthority> collect = permissions.stream().map(item -> new SimpleGrantedAuthority(item)).collect(Collectors.toList());
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username,null,collect);
        context.setAuthentication(authenticationToken);
        //4. 放行
        filterChain.doFilter(request,response);
    }
}
